<template>
  <Popover placement="bottomLeft" v-model:open="open" trigger="click">
    <template #content>
      <div :class="Styles.cronWrap">
        <Tabs v-model:active-key="active">
          <TabPane v-for="tab in tabs" :key="tab.tabKey" :tab="tab.tab">
            <component :is="tab.component" />
          </TabPane>
        </Tabs>
        <Divider />
        <Flex justify="space-between">
          <span>{{ cron }}</span>
          <Space>
            <Button @click="open = false">取消</Button>
            <Button type="primary" @click="onSave">保存</Button>
          </Space>
        </Flex>
      </div>
    </template>
    <slot />
  </Popover>
</template>

<script setup lang="tsx">
import { type Component, computed, provide, ref } from 'vue';
import {
  Button,
  ConfigProvider,
  Divider,
  Flex,
  Input,
  Popover,
  Space,
  TabPane,
  TabPaneProps,
  Tabs,
} from 'ant-design-vue';
import { emitKey } from './constant';
import day from './day.vue';
import hour from './hour.vue';
import Styles from './index.module.scss';
import minute from './minute.vue';
import month from './month.vue';
import second from './second.vue';
import year from './year.vue';

defineOptions({
  name: 'BCron',
});

const emit = defineEmits<{
  confirm: [value: string];
}>();

const modelValue = defineModel<string>();

const s = ref('*');
const m = ref('*');
const h = ref('*');
const D = ref('*');
const M = ref('*');
const W = ref('?');
const Y = ref('*');

const cron = computed(() => {
  return `${s.value} ${m.value} ${h.value} ${D.value} ${M.value} ${W.value} ${Y.value}`;
});

provide(emitKey, (data) => {
  const { type, value } = data;
  switch (type) {
    case 's':
      s.value = value;
      break;
    case 'm':
      m.value = value;
      break;
    case 'h':
      h.value = value;
      break;
    case 'D':
      D.value = value;
      break;
    case 'W':
      W.value = value;
      break;
    case 'M':
      M.value = value;
      break;
    case 'Y':
      Y.value = value;
      break;
  }
});

const open = ref<boolean>(false);
const onSave = () => {
  modelValue.value = cron.value;
  open.value = false;
  emit('confirm', modelValue.value);
};

const active = ref('s');
const tabs: Array<TabPaneProps & { component?: Component }> = [
  {
    tab: '秒',
    tabKey: 's',
    component: second,
  },
  {
    tab: '分',
    tabKey: 'm',
    component: minute,
  },
  {
    tab: '时',
    tabKey: 'h',
    component: hour,
  },
  {
    tab: '天',
    tabKey: 'D',
    component: day,
  },
  {
    tab: '月',
    tabKey: 'M',
    component: month,
  },
  {
    tab: '年',
    tabKey: 'Y',
    component: year,
  },
];
</script>
